package rm2;

import java.net.DatagramSocket;
import java.net.SocketException;

import threads.BuyItem;
import threads.CheckCustomerInfo;
import threads.CheckInfo;
import threads.CheckItemList;
import threads.ReturnItem;

/**
 * This class is the implementation object for your IDL interface.
 *
 * Let the Eclipse complete operations code by choosing 'Add unimplemented methods'.
 */
public class DRSInterfaServerImpl  {
	/**
	 * Constructor for DRSInterfaServerImpl 
	 */
	public DRSInterfaServerImpl() {
		super();
	}

	public String Buy(String customer_id, String item_id, int number,DRSserverinit drSserverinit)
			 {
		String reply;
		BuyItem bi = new BuyItem(customer_id, item_id, number,drSserverinit);
		reply = bi.Buy();
		
		return reply;
	}

	public String Return(String customer_id, String item_id, int number,DRSserverinit drSserverinit)
			 {
		String reply;
		ReturnItem ri = new ReturnItem(customer_id, item_id, number,drSserverinit);
		reply = ri.Return();
		
		return reply;
	}

	public String Check(String item_id,DRSserverinit drSserverinit)  {
		String reply;
		CheckItemList checklist = new CheckItemList(item_id,drSserverinit);
		//reply = checklist.start();	
		reply = checklist.checkItem(true);
		
		return reply;
	}

	public String Exchange(String customer_id, String bought_item_id,int bought_number, String desired_item_id, int desired_number, DRSserverinit drSserverinit)
			 {
	//	String reply = null;
	//	CheckInfo checklis = new CheckInfo();
		//reply = checklist.start();	
		//if(checklis.CheckBoughtItem(customer_id, bought_item_id,  bought_number))
		//{
			//if(checklis.CheckDesiredItem(customer_id, desired_item_id, desired_number))
			//{
				//this.Return(customer_id, bought_item_id, bought_number);
				//this.Buy(customer_id, desired_item_id, desired_number);
				//reply = "successful";
			//}
			//else
			//{
				//reply = " Unsuccessful Desired Item doesn't exist";
			//}
		//}else
		//{
			//reply = "Unsuccessful Customer " + customer_id +" haven't bought the item " + bought_item_id;
		//}
		//return reply;
	//}
		
		String reply;
		
		CheckItemList checklist = new CheckItemList(desired_item_id,drSserverinit);		
		reply = checklist.checkItem(true);		
		
		if(checklist.maxAvailable(reply) >= desired_number)
		{
			ReturnItem ri = new ReturnItem(customer_id, bought_item_id, bought_number,drSserverinit);
			reply = ri.Return();
			System.out.println("hello return"+ reply);
			
			if(reply.toLowerCase().contains("0"))
			{
				reply = "0";
				System.out.println("hello return after  0"+ reply);
			}	
			else
			{
				BuyItem bi = new BuyItem(customer_id, desired_item_id, desired_number,drSserverinit);
				reply = bi.Buy();
				System.out.println("hello buy"+ reply);
			}
		}
		else
			reply = "0";

		
		return reply;
	}		
}

